<template>
	<view class="aics-container">
		<!-- 新增转人工状态提示 -->
		<view v-if="isHumanMode" class="human-mode-indicator">
			<text>人工客服服务中 (会话ID: {{ humanSessionId }})</text>
		</view>
		<!-- 使用scroll-view组件替代普通view -->
		<scroll-view class="chat-message-list" ref="messageList" scroll-y="true" :scroll-into-view="scrollTopId"
			v-if="chatMessages.length > 0" @resize="handleResize">
			<view v-for="(message, index) in chatMessages" :key="index" :id="'msg-' + index"
				:class="message.type === 'user' ? 'user-message' : 'ai-message'">
				<view class="message-content">{{ message.content }}</view>
			</view>
		</scroll-view>

		<!-- 空状态提示 -->
		<view v-else class="empty-message">
			请输入消息开始对话
		</view>

		<!-- 修改输入区域 -->
		<view class="input-section">
			<input v-model="inputMessage" placeholder="请输入您的问题..." class="input-field" />
			<view v-if="!isHumanMode" class="send-btn" @click="sendMessage">发送</view>
			<view v-else class="send-btn" @click="sendHumanMessage">发送</view>
			<view class="transfer-btn" @click="switchToHumanService">转人工</view>
		</view>
	</view>
</template>

<script>
import { request } from '../../util/request.js';
export default {
	data() {
		return {
			chatMessages: [],
			inputMessage: '',
			isMounted: false,
			resizeTimer: null,
			isMiniProgram: false,
			scrollTopId: '',
			showDeclaration: true,
			// 新增数据项
			isHumanMode: false,
			humanSessionId: '',
			humanMessageHistory: [],
			humanPollingTimer: null,
			socketTask: null
		}
	},
	methods: {
		initHumanWebSocket() {
			if (!this.humanSessionId) return;
    
			// 小程序环境使用uni.connectSocket
			if (this.isMiniProgram) {
				this.socketTask = uni.connectSocket({
					url: `ws://127.0.0.1:8010/ws/customer-service/${this.humanSessionId}?role=user`,
					success: () => {
						console.log('WebSocket连接成功');
						// 恢复消息接收处理逻辑
						uni.onSocketMessage(res => {
							const message = JSON.parse(res.data);
							this.chatMessages.push({
								type: 'ai',
								content: message.content
							});
						});
					},
					fail: (err) => {
						console.error('WebSocket连接失败:', err);
						uni.showToast({
							title: '客服连接失败: ' + err.errMsg,
							icon: 'error'
						});
						this.socketTask = null;
					}
				});
			}
			// H5环境使用原生WebSocket
			else {
				this.websocket = new WebSocket(
					`ws://${location.host}/ws/customer-service/${this.humanSessionId}?role=user`
				);

				this.websocket.onmessage = (event) => {
					const message = JSON.parse(event.data);
					if (!message.isSelf) {
						this.chatMessages.push({
							type: 'ai',
							content: message.content
						});
					}
				};
			}
		},
		// 轮询获取客服回复
		// startPollingHumanMessages() {
		// 	this.humanPollingTimer = setInterval(async () => {
		// 		if (!this.isHumanMode || !this.humanSessionId) return;

		// 		const resp = await request({
		// 			url: 'owner-server/owner/human/messages',
		// 			method: 'GET',
		// 			data: { sessionId: this.humanSessionId }
		// 		});

		// 		if (resp.code === 200) {
		// 			// 获取最新消息（最后一条）
		// 			const allMessages = resp.data;
		// 			if (allMessages.length > this.chatMessages.filter(m => m.type === 'ai').length) {
		// 				const lastMessage = allMessages[allMessages.length - 1];

		// 				// 检查是否是客服消息且未显示
		// 				if (lastMessage.includes('客服:') &&
		// 					!this.chatMessages.some(m => m.content === lastMessage.split('客服: ')[1])) {

		// 					this.chatMessages.push({
		// 						type: 'ai',
		// 						content: lastMessage.split('客服: ')[1]
		// 					});
		// 				}
		// 			}
		// 		}
		// 	}, 3000); // 每3秒轮询一次
		// },
		sendMessage() {
			if (this.inputMessage.trim() === '') return;

			const message = this.inputMessage;
			this.inputMessage = '';

			// 检查是否需要转人工
			if (message.includes('转人工客服')) {
				this.switchToHumanService();
				return;
			}

			this.$nextTick(() => {
				this.chatMessages.push({
					type: 'user',
					content: message
				});

				// 确保DOM更新完成后再获取AI回复
				this.$nextTick(() => {
					this.getAIResponse(message);
				});
			});
		},
		showDeclarationModal() {
			uni.showModal({
				title: '服务声明',
				content: '使用的AI模型：deepseek-chat\n转人工方式：服务降级自动转人工/输入"转人工客服"关键词\n免责声明：本AI客服提供的信息仅供参考，不构成任何决策依据。',
				showCancel: false,
				confirmText: '我已知晓',
				success: () => {
					this.showDeclaration = false;
				}
			});
		},
		async switchToHumanService() {
			if (this.inputMessage.trim() === '') {
				uni.showToast({
					title: '请输入问题后再转人工',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({ title: '转接中...' });

			const resp = await request({
				url: 'owner-server/owner/transferToHuman',
				method: 'POST',
				data: this.inputMessage
			});

			if (resp.code === 200) {
				this.humanSessionId = resp.data; // 先设置会话ID
				this.initHumanWebSocket(); // 再初始化WebSocket
				this.isHumanMode = true;
				this.inputMessage = '';

				this.chatMessages.push({
					type: 'system',
					content: '已为您转接人工客服，请描述您的问题'
				});
				uni.hideLoading();
				uni.showToast({
					title: '已切换到人工客服',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: '转人工失败，请稍后再试',
					icon: 'error'
				});
			}
			uni.hideLoading();
			//this.startPollingHumanMessages();
		},
		// 发送人工服务消息
		sendHumanMessage() {
			if (!this.inputMessage.trim()) return;

			const message = this.inputMessage;
			this.inputMessage = '';
			this.chatMessages.push({ type: 'user', content: message });

			// 小程序环境
			console.log(this.socketTask);
			if (this.isMiniProgram && this.socketTask) {
				uni.sendSocketMessage({
					data: JSON.stringify({
						content: message,
						sessionId: this.humanSessionId,
						sender: "用户"
					})
				});
			}
			// H5环境
			else if (this.websocket) {
				this.websocket.send(JSON.stringify({
					content: message,
					sessionId: this.humanSessionId,
					sender: "用户"
				}));
			}
		},
		async getAIResponse(userMessage) {
			uni.showLoading({
				title: '输入中...'
			});

			console.log('userMessage:' + userMessage);
			const resp = await request({
				url: 'owner-server/owner/deepSeek',
				method: 'POST',
				data: userMessage,
				setTimeout: 20000
			})
			console.log('resp:' + resp.data);

			if (resp.code === 200) {
				uni.hideLoading();
				setTimeout(() => {
					const aiResponse = resp.data;

					this.chatMessages.push({
						type: 'ai',
						content: aiResponse
					});

					this.$nextTick(() => {
						this.scrollToBottom();
					});
				}, 300);
			} else if (resp.code === 9006) {
				// AI服务降级处理
				uni.hideLoading();
				this.isHumanMode = true;
				this.humanSessionId = resp.data;
				uni.showToast({
					title: 'AI服务暂不可用，已为您切换至人工客服',
					icon: 'none',
					duration: 3000
				});
				this.humanMessageHistory.push({
					type: 'system',
					content: '已为您转接人工客服，请描述您的问题'
				});
				this.switchToHumanService();
			}
		},
		scrollToBottom() {
			if (!this.isMounted) return;

			if (this.isMiniProgram) {
				// 确保每条消息都有唯一ID
				const lastMsgId = 'msg-' + (this.chatMessages.length - 1);

				// 设置scroll-into-view属性
				this.scrollTopId = lastMsgId;

				// 使用uni-app的API确保滚动
				const query = uni.createSelectorQuery().in(this);
				query.select('.chat-message-list').boundingClientRect(rect => {
					if (rect) {
						// 使用uni.pageScrollTo确保页面滚动
						uni.pageScrollTo({
							scrollTop: rect.bottom,
							duration: 0
						});

						// 额外延迟确保渲染完成
						setTimeout(() => {
							// 尝试通过ref获取scroll-view组件
							const scrollView = this.$refs.messageList;
							if (scrollView && scrollView.scrollIntoView) {
								scrollView.scrollIntoView({
									selector: '#' + lastMsgId
								});
							}
						}, 100);
					}
				}).exec();
			} else {
				// 非小程序环境使用原生scrollTop
				const container = this.$refs.messageList;
				if (container && container.scrollHeight) {
					container.scrollTop = container.scrollHeight;
				}
			}
		},
		handleResize() {
			clearTimeout(this.resizeTimer);
			this.resizeTimer = setTimeout(() => {
				this.scrollToBottom();
			}, 100);
		}
	},
	watch: {
		chatMessages: {
			handler() {
				this.scrollToBottom();
			},
			deep: true
		}
	},
	onLoad() {
		// 更准确地检测小程序环境
		this.isMiniProgram = typeof uni !== 'undefined' && !!uni.getSystemInfo;
		console.log('运行环境:', this.isMiniProgram ? '小程序' : '非小程序');
		this.showDeclarationModal();
	},
	mounted() {
		// 非小程序环境使用mounted
		if (!this.isMiniProgram) {
			this.$nextTick(() => {
				this.isMounted = true;
				this.scrollToBottom();
			});
		}
	},
	onReady() {
		// 小程序环境使用onReady
		if (this.isMiniProgram) {
			this.$nextTick(() => {
				this.isMounted = true;
				this.scrollToBottom();
			});
		}
	},
	beforeDestroy() {
		clearTimeout(this.resizeTimer);
		clearInterval(this.humanPollingTimer);
	}
}
</script>

<style scoped>
.aics-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
}

.chat-message-list {
	flex: 1;
	padding: 10px;
	height: 0;
}

.empty-message {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	color: #999;
}

.user-message {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 10px;
	margin-right: 20px;
}

.ai-message {
	display: flex;
	justify-content: flex-start;
	margin-bottom: 10px;
}

.message-content {
	padding: 10px;
	border-radius: 5px;
	max-width: 70%;
}

.user-message .message-content {
	background-color: #e1f5fe;
}

.ai-message .message-content {
	background-color: #f1f8e9;
}

.input-section {
	display: flex;
	padding: 10px;
	margin-bottom: 20px;
	border-top: 1px solid #e5e5e5;
}

.input-field {
	flex: 1;
	padding: 10px;
	border: 1px solid #e5e5e5;
	border-radius: 5px;
	margin-right: 10px;
}

.send-btn {
	padding: 10px 20px;
	background-color: #2979ff;
	color: #fff;
	border-radius: 5px;
	cursor: pointer;
}

.transfer-btn {
	padding: 10px 15px;
	background-color: #ff4d4f;
	color: #fff;
	border-radius: 5px;
	cursor: pointer;
	margin-left: 10px;
}

/* 新增样式 */
.human-mode-indicator {
	padding: 10px;
	background-color: #fef0f0;
	color: #f56c6c;
	text-align: center;
	font-size: 14px;
}
</style>